<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card class="box-card">
            <!-- 搜索和添加区域 -->
            <el-row :gutter="20">
                <!-- span栅格总长度24 gutter是栅格之间的间隔 -->
                <el-col :span='8'>
                    <el-input  placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList" ></el-button>
                    </el-input>
                </el-col>
                <el-col :span='4'>
                    <el-button type="primary" @click="dialogFormVisible=true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区 -->
            <el-table :data='userList' border stripe>
                <el-table-column type='index'></el-table-column>
                <el-table-column label='姓名' prop='username'></el-table-column>
                <el-table-column label='邮箱' prop='email'></el-table-column>
                <el-table-column label='电话' prop='mobile'></el-table-column>
                <el-table-column label='角色' prop='role_name'></el-table-column>
                <el-table-column label='状态' >
                    <!-- 如果同时指定了prop和插槽，插槽会覆盖掉prop -->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label='操作'>
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type='primary' icon='el-icon-edit' @click="showEditDialog(scope.row.id)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type='danger' icon='el-icon-delete' @click="removeUserById(scope.row.id)"></el-button>
                        <!-- 分配角色按钮 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top">
                            <el-button type='warning' icon='el-icon-setting' @click="roleSet(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页列表区域 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[10, 20, 30,50]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="dialogFormVisible" @close="addDialogClosed">
            <el-form :model="addForm" :rules="rules" ref="addFormRef">
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                    <el-input v-model="addForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                    <el-input v-model="addForm.password" autocomplete="off" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                    <el-input v-model="addForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
                    <el-input v-model.number="addForm.mobile" autocomplete="off" ></el-input>
                </el-form-item>
            </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button  @click="dialogFormVisible=false">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </div>
        </el-dialog>

        <!-- 修改用户信息对话框 -->
        <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" @close="editDialogClosed">
            <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
                <el-form-item label="用户名">
                    <el-input type="username" v-model="editForm.username" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input  v-model="editForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model.number="editForm.mobile"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editUserInfo">提交</el-button>
                    <el-button @click="editDialogVisible=false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 分配角色的对话框 -->
        <el-dialog
            title="分配角色"
            :visible.sync="setRoleDialogVisible"
            width="30%"
            @close="setRoleClosed">
            <div>
                <p>当前的用户: {{ userInfo.username }}</p>
                <p>当前的角色: {{ userInfo.role_name }}</p>
                <p>分配新角色:
                    <el-select v-model="selectRoleId" placeholder="请选择">
                        <!-- v-model把用户选中的值双向同步到数据中 :label我们所看到的名称 :value数据信息中真正选中值  -->
                        <el-option
                            v-for="item in rolesList"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo" >确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
export default {
    data() {
        // 验证手机号的规则
        var checkMobile = (rule, value, callback) => {
            const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
            if(regMobile.test(value)) {
                return callback();
            }
            callback(Error("请输入合法的手机号"))
        }
        return {
            // 获取用户列表的参数
            queryInfo: {
                query: '',
                // 当前的页数
                pagenum: 1,
                // 当前每页显示多少条数据
                pagesize: 10,
            },
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            // 查询到的用户信息对象
            editForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }           
                ],
                mobile: [
                    { required: true, message: '请输入活动名称', trigger: 'blur'},
                    { validator: checkMobile}
                ],
            },
            // 存储获取到的用户信息
            userList: [],
            total: 0,
            dialogFormVisible: false,
            formLabelWidth: '120px',
            editDialogVisible: false,
            setRoleDialogVisible: false,        //控制分配角色对话框的显示和隐藏
            userInfo: {},                       //需要被分配角色信息的用户
            rolesList: [],                      //所有角色的数据列表
            selectRoleId: '',                   //已选中的角色(表面上点击的是角色,实际上选中的是id值)

        }
    },
    created() {
        this.getUserList();
    },
    methods: {
        async getUserList() {
            const {data:res} = await this.$http.get('users',{params: this.queryInfo})
            console.log(res);
            if(res.meta.status !== 200) return this.$message.error(res.meta.message)
            this.userList = res.data.users;
            this.total = res.data.total;
        },
        // 监听pagesize改变的事件
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize;
            this.getUserList();
        },
        // 监听页码值改变的事件
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.getUserList();
        },
        // 监听switch状态的改变
        async userStateChange(userInfo) {
            console.log(userInfo);
            const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if(res.meta.status !== 200) {
                // 如果状态修改失败，就让状态值取反，保持原状态不变
                userInfo.mg_state = !userInfo.mg_state;
                this.$message.error("状态修改失败");
            }
            this.$message.success("状态修改成功")
        },
        // 监听用户对话框的事件
        addDialogClosed() {
            this.$refs.addFormRef.resetFields();
        },
        // 点击按钮，添加新用户
        addUser() {
            // 提交的表单数据进行预校验
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return;
                // 可以发起添加用户的网络请求
                const { data: refs } = await this.$http.post('users',this.addForm)
                if(refs.meta.status !== 201) {
                    this.$message.error("用户添加失败")
                }
                // 隐藏添加用户的对话框
                this.dialogFormVisible=false
                // 重新获取用户列表数据
                this.getUserList();
            })
        },
        // 展示编辑用户信息的对话框
        async showEditDialog(id) {
            const { data: res } = await this.$http.get('users/' + id)
            if(res.meta.status !== 200) {
                return this.$message.error("查询用户信息失败")
            }
            this.editForm = res.data;
            console.log(this.editForm);
            this.editDialogVisible = true;
        },
        // 监听修改用户对话框的关闭事件
        editDialogClosed() {
            this.$refs.editFormRef.resetFields();
        },
        // 修改用户信息并提交
        editUserInfo() {
            this.$refs.editFormRef.validate(async valid => {
                if(!valid) return
                // 校验成功，发起修改用户信息的请求
                // this.$http.put(...)返回一个promise格式的数据
                const { data: resp } = await this.$http.put('users/' + this.editForm.id, { 
                                        email: this.editForm.email, 
                                        mobile: this.editForm.mobile })
                console.log(resp);
                if(resp.meta.status != 200) {
                    this.$message.error("用户信息修改失败")
                }
                // 关闭对话框
                // 刷新数据信息
                // 提示修改成功
                this.editDialogVisible = false;
                this.getUserList();
                this.$message.success("用户信息修改成功")

            })
        },
        // 根据id删除对应的用户信息
        async removeUserById(id) {
            // 弹框询问是否删除
            // 如果用户确认删除，则字符串为confirm;如果用户取消了删除，则返回值为cancel
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
            }).catch(() => {            //  }).catch(err => err)
                    this.$message({
                    type: 'info',
                    message: '已取消删除'
                });     
            });
            const { data: resp } = await this.$http.delete('users/' + id);
            if(resp.meta.status != 200) return this.$message.error(resp.meta.msg)
            this.$message.success(resp.meta.msg)
            this.getUserList();
        },
        // 展示分配角色对话框
        async roleSet(userInfo) {
            this.userInfo = userInfo
            // 在展示对话框之前,获取所有的角色列表
            const { data: res  } = await this.$http.get(`roles`)
            if(res.meta.status !== 200) {
                return this.$message.error("角色信息获取失败")
            }
            this.rolesList = res.data;
            this.setRoleDialogVisible=true;
        },
        // 点击按钮 分配角色
        async saveRoleInfo() {
            //  selectRoleId
            if(!this.selectRoleId) {
                return this.$message.error("请选择要分配的角色")
            }

            const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,{ rid: this.selectRoleId})
            if(res.meta.status !== 200) {
                return this.$message.error("角色分配失败")
            }
            this.$message.success("角色分配成功")
            this.getUserList();
            this.setRoleDialogVisible=false
        },
        setRoleClosed() {
            this.selectRoleId=''
            this.userInfo=[]
        }
    }
    
}
</script>
<style lang="less" scoped>
    
</style>